package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.BusinessException;
import com.mall.common.ResultCode;
import com.mall.model.Product;
import com.mall.repository.ProductMapper;
import com.mall.service.ProductService;
import org.springframework.stereotype.Service;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    
    @Override
    public void createProduct(Product product) {
        // 设置默认状态
        product.setStatus(1);
        // 保存商品
        save(product);
    }
    
    @Override
    public void updateProduct(Product product) {
        // 检查商品是否存在
        if (!exists(product.getId())) {
            throw new BusinessException(ResultCode.PRODUCT_NOT_EXIST);
        }
        // 更新商品
        updateById(product);
    }
    
    @Override
    public void deleteProduct(Long id) {
        // 检查商品是否存在
        if (!exists(id)) {
            throw new BusinessException(ResultCode.PRODUCT_NOT_EXIST);
        }
        // 删除商品
        removeById(id);
    }
    
    @Override
    public Page<Product> getProductPage(Page<Product> page, Long categoryId) {
        // 构建查询条件
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (categoryId != null) {
            wrapper.eq(Product::getCategoryId, categoryId);
        }
        wrapper.orderByDesc(Product::getCreateTime);
        // 分页查询
        return page(page, wrapper);
    }
    
    @Override
    public void updateStock(Long id, Integer stock) {
        // 检查商品是否存在
        if (!exists(id)) {
            throw new BusinessException(ResultCode.PRODUCT_NOT_EXIST);
        }
        // 检查库存是否足够
        Product product = getById(id);
        if (product.getStock() < stock) {
            throw new BusinessException(ResultCode.PRODUCT_STOCK_INSUFFICIENT);
        }
        // 更新库存
        product.setStock(product.getStock() - stock);
        updateById(product);
    }
    
    private boolean exists(Long id) {
        return count(new LambdaQueryWrapper<Product>()
                .eq(Product::getId, id)) > 0;
    }
} 